#ifndef TRACKVIEW_H
#define TRACKVIEW_H

#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsPathItem>
#include <QTimer>
#include <QList>
#include <QPointF>
#include "vehicle.h"
#include "qpainterpathhelper.hpp"

#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

class TrackView : public QGraphicsView
{
    Q_OBJECT

public:
    explicit TrackView(QWidget *parent = nullptr);
    
    // 轨道参数
    qreal radius() const { return m_radius; }
    void setRadius(qreal radius);
    
    qreal straightLength() const { return m_straightLength; }
    void setStraightLength(qreal length);
    
    // 小车管理
    void addVehicle(const QColor &color = Qt::blue, qreal size = 20.0);
    void removeVehicle(int index);
    void removeSelectedVehicle();
    Vehicle* vehicleAt(int index) const;
    int vehicleCount() const;
    
    // 动画控制
    void startAnimation();
    void stopAnimation();
    bool isAnimating() const { return m_timer->isActive(); }
    
    // 设置动画速度
    void setAnimationSpeed(qreal speed) { m_animationSpeed = speed; }
    
signals:
    void vehicleMoved(Vehicle *vehicle, const QPointF &pos);
    
protected:
    void drawBackground(QPainter *painter, const QRectF &rect) override;
    void resizeEvent(QResizeEvent *event) override;
    void mousePressEvent(QMouseEvent *event) override;
    void mouseMoveEvent(QMouseEvent *event) override;
    void mouseReleaseEvent(QMouseEvent *event) override;
    
private slots:
    void animateVehicles();
    
private:
    void updateTrackPath();
    QPointF getPointOnTrack(qreal position) const;
    qreal getTrackLength() const;
    qreal findClosestPosition(const QPointF &point) const;
    
    QGraphicsScene *m_scene;
    QGraphicsPathItem *m_trackItem;
    QTimer *m_timer;
    
    qreal m_radius;
    qreal m_straightLength;
    qreal m_animationSpeed;
    
    QList<Vehicle*> m_vehicles;
    Vehicle *m_draggedVehicle;
    QPointF m_dragOffset;
    bool m_isDragging;
};

#endif // TRACKVIEW_H
